﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;//语音识别

namespace Note_Assistant
{
    public partial class NoteEditorForm : Form
    {
        private SpeechRecognitionEngine speechRecognizer;
        private bool isListening = false;

        private StatusStrip statusStrip;
        // 在InitializeEditor方法中添加语音输入按钮

        private Note currentNote;
        //临时图片存储路径
        private string tempImagePath = Path.Combine(Path.GetTempPath(), "NoteImages");
        private TextBox titleTextBox;//标题文本框
        private RichTextBox contentRichTextBox;//内容富文本框，RTF格式

        public NoteEditorForm(Note note)
        {
            currentNote = note;
            InitializeEditor();
            LoadNoteContent();
        }
        //编辑器页面
        private void InitializeEditor()
        {
            this.statusStrip = new StatusStrip(); // 初始化

            this.Text = $"{currentNote.Title} - 笔记编辑器";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterScreen;

            var mainPanel = new Panel { Dock = DockStyle.Fill };
            //工具栏
            var toolStrip = new ToolStrip { Dock = DockStyle.Top };
            toolStrip.Items.Add(new ToolStripButton("保存", null, SaveNote_Click));
            toolStrip.Items.Add(new ToolStripButton("另存为", null, SaveAs_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("撤销", null, Undo_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("剪切", null, Cut_Click));
            toolStrip.Items.Add(new ToolStripButton("复制", null, Copy_Click));
            toolStrip.Items.Add(new ToolStripButton("粘贴", null, Paste_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("字体", null, Font_Click));
            toolStrip.Items.Add(new ToolStripButton("插入图片", null, InsertImage_Click));
            toolStrip.Items.Add(new ToolStripButton("插入日期", null, InsertDate_Click));

            titleTextBox = new TextBox
            {
                Dock = DockStyle.Top,//固定顶部
                Text = currentNote.Title,
                Font = new Font("微软雅黑", 12, FontStyle.Bold)
            };
            titleTextBox.TextChanged += Title_TextChanged;

            contentRichTextBox = new RichTextBox
            {
                Dock = DockStyle.Fill,
                AllowDrop = true,
            };
            //绑定拖放
            contentRichTextBox.DragEnter += RichTextBox_DragEnter;
            contentRichTextBox.DragDrop += RichTextBox_DragDrop;
            //状态栏
            var statusStrip = new StatusStrip { Dock = DockStyle.Bottom };
            statusStrip.Items.Add(new ToolStripStatusLabel("就绪…"));
            //控件添加到主面板
            mainPanel.Controls.Add(contentRichTextBox);
            mainPanel.Controls.Add(titleTextBox);
            this.Controls.AddRange(new Control[] { mainPanel, toolStrip, statusStrip });
            //创建临时图片目录
            Directory.CreateDirectory(tempImagePath);

            // 在工具栏添加语音输入按钮
            var voiceButton = new ToolStripButton("语音输入", null, VoiceInput_Click)
            {
                DisplayStyle = ToolStripItemDisplayStyle.Text,
                ToolTipText = "开始/停止语音输入 (Ctrl+Shift+V)"
            };
            toolStrip.Items.Add(voiceButton);

            // 添加快捷键支持
            this.KeyPreview = true;
            this.KeyDown += NoteEditorForm_KeyDown;

            // 初始化语音识别引擎
            InitializeSpeechRecognition();

            // 更新状态栏
            var statusStrip = new StatusStrip { Dock = DockStyle.Bottom };
            var statusLabel = new ToolStripStatusLabel("就绪");
            statusStrip.Items.Add(statusLabel);

            // 添加语音状态指示器
            var voiceStatus = new ToolStripStatusLabel
            {
                Text = "麦克风: 关闭",
                Image = Resources.MicOffIcon, // 需要添加图标资源
                Tag = "voice"
            };
            statusStrip.Items.Add(voiceStatus);

        }



        //加载笔记内容到编辑器
        private void LoadNoteContent()
        {
            try
            {
                if (!string.IsNullOrEmpty(currentNote.FilePath) && File.Exists(currentNote.FilePath))
                {
                    contentRichTextBox.Rtf = File.ReadAllText(currentNote.FilePath);
                }
                else if (!string.IsNullOrEmpty(currentNote.Content))
                {
                    contentRichTextBox.Rtf = currentNote.Content;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载笔记内容失败：{ex.Message}");
            }
        }
        //标题文本变化事件处理
        private void Title_TextChanged(object sender, EventArgs e)
        {
            currentNote.Title = titleTextBox.Text;
            this.Text = $"{currentNote.Title} - 笔记编辑器";
        }
        //拖放图片进入事件处理
        private void RichTextBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }
        //拖放完成
        private void RichTextBox_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string file in files)
                {
                    string ext = Path.GetExtension(file).ToLower();
                    if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                    {
                        InsertImageToContent(file);
                    }
                }
            }
        }
        //保存按钮
        private void SaveNote_Click(object sender, EventArgs e)
        {
            SaveNote();
        }
        //另存为按钮
        private void SaveAs_Click(object sender, EventArgs e)
        {
            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "RTF 文件|*.rtf";
                saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    string oldPath = currentNote.FilePath;
                    currentNote.SetFilePath(saveDialog.FileName);
                    SaveNote();
                }
            }
        }
        //保存笔记
        private void SaveNote()
        {
            currentNote.Content = contentRichTextBox.Rtf;
            currentNote.Save();
            this.Text = $"{currentNote.Title} - 已保存";
        }
        //窗体关闭前事件处理
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (contentRichTextBox.Modified)
            {
                var result = MessageBox.Show("笔记有未保存的更改，是否保存?", "提示",
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    SaveNote();
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
            // 释放语音识别资源
            if (speechRecognizer != null)
            {
                if (isListening)
                {
                    speechRecognizer.RecognizeAsyncStop();
                }
                speechRecognizer.Dispose();
            }

            base.OnFormClosing(e);
        }
        //撤销按钮
        private void Undo_Click(object sender, EventArgs e)
        {
            if (contentRichTextBox.CanUndo)
            {
                contentRichTextBox.Undo();
            }
        }
        //剪切
        private void Cut_Click(object sender, EventArgs e)
        {
            contentRichTextBox.Cut();
        }
        //复制
        private void Copy_Click(object sender, EventArgs e)
        {
            contentRichTextBox.Copy();
        }
        //粘贴
        private void Paste_Click(object sender, EventArgs e)
        {
            contentRichTextBox.Paste();
        }
        //设置字体
        private void Font_Click(object sender, EventArgs e)
        {
            using (var fontDialog = new FontDialog())
            {
                if (fontDialog.ShowDialog() == DialogResult.OK)
                {
                    contentRichTextBox.SelectionFont = fontDialog.Font;
                }
            }
        }
        //插入图片按钮
        private void InsertImage_Click(object sender, EventArgs e)
        {
            using (var openDialog = new OpenFileDialog())
            {
                openDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    InsertImageToContent(openDialog.FileName);
                }
            }
        }
        //插入图片实际实现
        private void InsertImageToContent(string imagePath)
        {
            try
            {
                var tempFile = Path.Combine(tempImagePath, Path.GetFileName(imagePath));
                File.Copy(imagePath, tempFile, true);
                Clipboard.SetImage(Image.FromFile(tempFile));
                contentRichTextBox.Paste();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"插入图片失败：{ex.Message}");
            }
        }
        //插入日期
        private void InsertDate_Click(object sender, EventArgs e)
        {
            contentRichTextBox.SelectedText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void InitializeSpeechRecognition()
        {
            try
            {
                speechRecognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("zh-CN"));

                // 创建语法规则
                var grammarBuilder = new GrammarBuilder();
                grammarBuilder.AppendDictation();

                // 加载语法
                var grammar = new Grammar(grammarBuilder);
                speechRecognizer.LoadGrammar(grammar);

                // 设置事件处理
                speechRecognizer.SpeechRecognized += SpeechRecognized;
                speechRecognizer.SpeechHypothesized += SpeechHypothesized;
                speechRecognizer.SpeechRecognitionRejected += SpeechRejected;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"语音识别初始化失败: {ex.Message}");
            }
        }

        private void VoiceInput_Click(object sender, EventArgs e)
        {
            ToggleVoiceInput();
        }

        private void ToggleVoiceInput()
        {
            if (speechRecognizer == null)
            {
                MessageBox.Show("语音识别引擎未正确初始化");
                return;
            }

            try
            {
                if (!isListening)
                {
                    speechRecognizer.SetInputToDefaultAudioDevice();
                    speechRecognizer.RecognizeAsync(RecognizeMode.Multiple);
                    statusStrip.Items[0].Text = "正在聆听...";
                    isListening = true;
                }
                else
                {
                    speechRecognizer.RecognizeAsyncStop();
                    statusStrip.Items[0].Text = "语音输入已停止";
                    isListening = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"语音识别错误: {ex.Message}");
            }

            // 更新状态栏图标
            var voiceStatus = statusStrip.Items.Cast<ToolStripItem>()
                .FirstOrDefault(item => item.Tag?.ToString() == "voice");

            if (voiceStatus != null)
            {
                if (!isListening)
                {
                    voiceStatus.Text = "麦克风: 开启";
                    voiceStatus.Image = Resources.MicOnIcon;
                }
                else
                {
                    voiceStatus.Text = "麦克风: 关闭";
                    voiceStatus.Image = Resources.MicOffIcon;
                }
            }
        }

        private void SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (e.Result.Confidence > 0.7) // 置信度阈值
            {
                this.Invoke((MethodInvoker)delegate
                {
                    contentRichTextBox.SelectedText = e.Result.Text + " ";
                    statusStrip.Items[0].Text = "已输入语音内容";
                });
            }
        }

        private void SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                statusStrip.Items[0].Text = "正在识别: " + e.Result.Text;
            });
        }

        private void SpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                statusStrip.Items[0].Text = "未识别到有效语音";
            });
        }

        private void NoteEditorForm_KeyDown(object sender, KeyEventArgs e)
        {
            // 添加快捷键 Ctrl+Shift+V 切换语音输入
            if (e.Control && e.Shift && e.KeyCode == Keys.V)
            {
                ToggleVoiceInput();
                e.Handled = true;
            }
        }

    }
}
